import { RefIndex } from '../util/ref-index'
import { getEntityList } from '../base'
import type { Airport } from '../airport'
import type { Waypoint } from '../waypoint'
import { SegmentItemIndex } from '../util/segment'
import { makeRouteSegmentIndex, type WaypointSegmentIndex } from '../util/waypoint-segment'
import type { Routing } from './types'

export let routingIndex: SegmentItemIndex<Routing>
export let routingSegmentIndex: WaypointSegmentIndex<Routing>
export let routingByAirport: RefIndex<Airport, Routing>

export function initRoutingIndex(lst: Routing[]) {
  routingSegmentIndex = makeRouteSegmentIndex(lst)
  routingIndex = new SegmentItemIndex(routingSegmentIndex.segments())
  routingByAirport = new RefIndex(lst, (r) => {
    if (r.departureAirport) {
      if (r.arrivalAirport) {
        return [r.departureAirport, r.arrivalAirport]
      }
      return r.departureAirport
    }
    return r.arrivalAirport
  })
}

export function getAirportRoutingSet(apt: string): Set<Routing> | undefined {
  return routingByAirport.get(apt)
}

let routingByWaypoint: RefIndex<Waypoint, Routing>

export function getWaypointRoutingSet(wpt: string): Set<Routing> | undefined {
  let s = routingByWaypoint
  if (!s) {
    s = new RefIndex<Waypoint, Routing>(getEntityList<Routing>('Routing'), (r) => {
      return r.waypointList
    })
    routingByWaypoint = s
  }
  return s.get(wpt)
}
